package com.central.user.service.impl;

import com.central.model.common.PageResult;
import com.central.model.common.Result;
import com.central.user.dao.PlayerDao;
import com.central.user.dao.ServerDao;
import com.central.user.model.BlackListInfo;
import com.central.user.model.ServerInfo;
import com.central.user.service.ServerServiceI;
import com.central.user.util.SSHUtil;
import com.central.user.util.ServerUtil;
import com.central.user.util.SmsUtil;
import com.jcraft.jsch.JSchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ServerServiceImpl implements ServerServiceI {

    @Autowired
    private ServerDao serverDao;

    private Integer code;

    private Timer timer;

    @Override
    public PageResult<ServerInfo> getsServerInfo() {
        List<ServerInfo> list = new ArrayList<>();
        list = serverDao.getServerInfo();
        int tolat = serverDao.getServerCount();
        return PageResult.<ServerInfo>builder().data(list).code(0).count((long)1).build();
    }

    @Override
    public Result closeServer(String ip) {
        try {
            return Result.succeed(ServerUtil.exeScriptClose(ip));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("执行失败");
        }
    }

    @Override
    public Result startServer(String ip) {
        try {
            return Result.succeed(ServerUtil.exeScriptStary(ip));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("执行失败");
        }
    }

    @Override
    public Result getCode(String phone) {
        if (timer == null){
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    code = null;
                }
            },30*60*1000);
        }
        try {
            if (code == null){
                code = (int)((Math.random()*9+1)*100000);
                System.out.println(" 验证码是 : " + code);
//                int smsCode = Integer.parseInt(SmsUtil.sendSms(phone,"您的验证码是：" + String.valueOf(code) + " 验证码有效时间2分钟，请勿泄露给其他人。【宝石大乱斗】",null));
//                if (smsCode < 0){
//                    return Result.failed(-1,"获取验证码失败");
//                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("获取验证码失败");
        }
        return Result.succeed("成功");
    }

    @Override
    public Result verifyCode(int data) {
        if (code != null){
            if (data == code){
                return Result.succeed("验证成功");
            }else {
                return Result.failed("验证失败");
            }
        }else{
            return Result.failed("验证码失效");
        }
    }
}
